package com.ligong.gptai.adopter;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ligong.gptai.dto.ChatImage;
import com.ligong.gptai.dto.ChatMessage;
import com.ligong.gptai.dto.ChatMessageStream;
import com.ligong.gptai.service.OpenAIService;

@Service
public class OpenAiServiceAdopter implements IAIServiceAdopter {
    @Autowired
    private OpenAIService openAIService;

    public ChatMessage sendText(String model, String message) {
        try {
            Map messageMap = openAIService.sendText(model, message);

            // 适配
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setId(messageMap.get("id").toString());

            List<Map> outputList = (List<Map>) messageMap.get("output");

            List<Map> completedList = outputList.stream().filter(x -> x.get("status").toString().equals("completed"))
                    .toList();

            if (completedList.size() > 0) {
                List<Map> contentList = (List<Map>) completedList.get(0).get("content");
                chatMessage.setMessage(contentList.get(0).get("text").toString());
            }

            chatMessage.setRole("assistant");
            return chatMessage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void sendText(String model, String message, Boolean stream, Consumer<ChatMessageStream> onDelta) {
        openAIService.sendText(model, message, stream, (str) -> {
            ChatMessageStream chatMessageStream = new ChatMessageStream();
            chatMessageStream.setDelta(str);
            chatMessageStream.setId(UUID.randomUUID().toString());
            onDelta.accept(chatMessageStream);
        });
    }

    public ChatImage createImage(String model, String prompt, Integer n, String size) {
        try {
            Map imageMap = openAIService.createImage(model, prompt, n, size);
            List<Map> dataList = (List<Map>) imageMap.get("data");
            Map data = dataList.get(0);

            ChatImage chatImage = new ChatImage();
            chatImage.setId(UUID.randomUUID().toString());
            chatImage.setImage(data.get("url").toString());

            return chatImage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
